package org.noidler.codex;

import com.mongodb.MongoClientSettings;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.InsertManyResult;
import com.mongodb.client.result.InsertOneResult;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.conversions.Bson;

import java.util.List;

import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;

public class MongoDbCollection<T> {
    private MongoDatabase database;
    private MongoCollection<T> collection;

    CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),CodecRegistries.fromProviders(
            PojoCodecProvider.builder().register("org.noidler.model").build())
    );

    public MongoDbCollection(MongoDbClient mongoDbClient, String databaseName, String collectionName, Class<T> clazz) {
        database = mongoDbClient.getMongoClient().getDatabase(databaseName);
        collection = database.getCollection(collectionName, clazz).withCodecRegistry(codecRegistry);
    }

    public InsertOneResult insertOne(T document) {
        return collection.insertOne(document);
    }

    public InsertManyResult insertMany(List<T> documents) {
        return collection.insertMany(documents);
    }

    public FindIterable<T> find(Bson filter) {
        return collection.find(filter);
    }

}
